package io.github.harmonly.service.impl;

import io.github.harmonly.entity.association.Association;
import io.github.harmonly.entity.association.Member;
import io.github.harmonly.entity.User;
import io.github.harmonly.mapper.AssociationMapper;
import io.github.harmonly.mapper.MemberMapper;
import io.github.harmonly.mapper.UserMapper;
import io.github.harmonly.service.MemberService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {

    @Resource
    private MemberMapper memberMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AssociationMapper associationMapper;

    @Override
    public List<Association> getAssociations(int uid) {
        List<Member> members = memberMapper.getMembersByUser(uid);
        List<Association> list = new ArrayList<>();
        members.forEach(member -> list.add(associationMapper.getAssociation(member.getAid())));
        associationMapper.getAssociations().forEach(association -> {
            if (association.getUid() == uid) list.add(association);
        });
        return list;
    }

    @Override
    public List<User> getUsers(int aid) {
        List<Member> members = memberMapper.getMembersByAssociation(aid);
        List<User> list = new ArrayList<>();
        members.forEach(member -> list.add(userMapper.getUser(member.getUid())));
        return list;
    }

    @Override
    public boolean addMember(Member member) {
        getAssociations(member.getUid());
        User user = userMapper.getUser(member.getUid());
        user.setRole("member");
        userMapper.editUser(user);
        return memberMapper.addMember(member) == 1;
    }

    @Override
    public boolean deleteMember(Member member) {
        if (getAssociations(member.getUid()).size() == 1) {
            User user = userMapper.getUser(member.getUid());
            user.setRole("student");
            userMapper.editUser(user);
        }
        return memberMapper.deleteMember(member) == 1;
    }

    @Override
    public boolean isJoin(Member member) {
        return memberMapper.isJoin(member) != null;
    }
}
